﻿using Autofac;
using Flies.SQLSugarCore.Tool;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Flies.SQLSugarCore
{
    public class AutoFacModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var serviceAssembly = Assembly.Load("Files.Services");
            builder.Register(context =>
            {
                // 尝试获取当前数据库连接
                var db = DbScoped.SugarScope;
#if DEBUG
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine($"SQL: {sql}");
                    Console.WriteLine($"Params: {string.Join(",", pars.Select(p => $"{p.ParameterName}={p.Value}"))}");
                };
#endif
                var entityTypes = ModuleHelper.GetEntityTypesFromAllModules();
                foreach (var entityType in entityTypes)
                {
                    if (entityType.IsAbstract || entityType.IsInterface)
                        continue;

                    try
                    {
                        db.DbMaintenance.CreateDatabase();
                        db?.CodeFirst.InitTables(entityType);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Init table failed for type {entityType.FullName}: {ex.Message}");
                    }
                }
                // 这里可以添加逻辑判断当前数据库连接是否有效
                try
                {
                    // 假设有一个简单的查询来验证连接的有效性
                    //db.Ado.GetScalar("SELECT * FROM ZZJG_XT_DWBM");


                }
                catch (Exception ex)
                {
                    Console.WriteLine($"主数据库连接失败: {ex.Message}");


                }

                return db;
            }).As<ISqlSugarClient>().SingleInstance();
            builder.RegisterAssemblyTypes(serviceAssembly)
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();
        }
    }
}
